import { getSceneShareList, getActLmState } from '@/api/scene';
import { calcExpirationTime } from '@/utils';
import { PaginationLayout } from '@/views/enum/common';
import { useRequest } from '@jl/common/composable';
import {
  IColumnConfig,
  IFormConfig,
  IFormData,
  IFormItemConfig,
  IJLDatagridInstance,
  IJlFormInstance,
  IPageConfig,
  ITableConfig,
} from '@jl/element-plus';
import { GetProListByMuCond } from '@/api/project';
import { SCENE_LOGICMARK_START } from '@/views/enum/scene';

const { run: proListRun, data: proData } = useRequest<any, any>(GetProListByMuCond, { list: [] });

const proListData = computed(() => {
  return [{ label: '全部', value: undefined }].concat(
    proData.value.list.map((item: any) => {
      return {
        label: item.projectName,
        value: item.projectId,
      };
    })
  );
});

export function list() {
  const formRef = ref<IJlFormInstance>();
  const tableData = ref<any>([]);
  const {
    run: lmRun,
    data: lmData,
    loading: lmLoading,
  } = useRequest<any, any>(
    getActLmState,
    [],
    {},
    {
      onSuccess: operateData,
    }
  );
  const { run, data, loading } = useRequest<any, any>(
    getSceneShareList,
    [{ list: [], total: 0 }],
    {},
    {
      onSuccess(res: any) {
        const resourceCodeMap = {} as any;
        res[0].list.forEach((v: any) => {
          if (!resourceCodeMap[v.resourceCode]) {
            resourceCodeMap[v.resourceCode] = v.resourceCode;
          }
        });
        const fData = new FormData();
        fData.set('actIds', Object.keys(resourceCodeMap).join(';'));
        lmRun({
          data: fData,
        });
      },
    }
  );
  const formConfig: IFormConfig = { gutter: 10, labelWidth: 80 };
  const formData = ref<IFormData>({
    shareName: '',
    projectName: undefined,
  });

  const formItemConfig = computed<IFormItemConfig>(() => [
    {
      type: 'input',
      key: 'shareName',
      label: '场景名称',
      span: 5,
      clearable: true,
      placeholder: '请输入',
      optionsWithAll: true,
    },
    {
      type: 'slot',
      slotName: 'projectNameSlot',
      key: 'projectName',
      label: '所属项目',
      span: 5,
      clearable: true,
      placeholder: '请选择',
      options: [],
      optionsWithAll: true,
    },
    {
      type: 'slot',
      slotName: 'searchSlot',
      key: 'search',
      label: '',
      span: 5,
      labelWidth: 10,
    },
  ]);

  const tableRef = ref<IJLDatagridInstance>();

  const tableConfig = ref<ITableConfig>({
    index: false,
    selection: false,
  });

  const pageConfig = ref<IPageConfig>({
    small: false,
    visible: true,
    layout: PaginationLayout,
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  });

  const tableColumn = ref<IColumnConfig[]>([
    { label: '序号', prop: 'serial', width: '120px' },
    { label: '场景名称', prop: 'shareName' },
    {
      label: '分享模式',
      prop: 'shareType',
      slotName: 'shareTypeSlot',
    },
    {
      label: '失效时间',
      prop: 'expirationTime',
      slotName: 'expirationTimeSlot',
    },
    { label: '访问次数', prop: 'accessTimes' },
    { label: '创建时间', prop: 'createTime', width: '250px', slotName: 'createTimeSlot' },
    { label: '操作', prop: 'operation', width: '160px', fixed: 'right', slotName: 'slotOperation' },
  ]);

  function operateData() {
    const logicMarkMap = {} as any;
    lmData.value.forEach((v: any) => {
      logicMarkMap[v.actId] = v.logicMarkState;
    });
    for (const [index, list] of data.value[0].list.entries()) {
      const expirationTimeResult = calcExpirationTime(list.expirationTime);
      const logicMark = logicMarkMap[list.resourceCode];
      if (logicMark !== undefined && logicMark !== SCENE_LOGICMARK_START) {
        list.shareStatus = 1;
      }
      list.expirationTimeName = list.shareStatus === 1 ? '已过期' : expirationTimeResult.name;
      list.expirationTimeState = list.shareStatus === 1 ? 3 : expirationTimeResult.code;
      list.serial = (pageConfig.value.currentPage - 1) * pageConfig.value.pageSize + index + 1;
    }
    tableData.value = data.value[0].list;
  }

  const search = async (flag = false) => {
    if (flag) {
      pageConfig.value.currentPage = 1;
    }
    const searchParam = {
      data: {
        pageNum: pageConfig.value.currentPage,
        pageSize: pageConfig.value.pageSize,
        shareName: formData.value.shareName,
        projectName: formData.value.projectName || '',
      },
    };
    await run(searchParam);
    pageConfig.value.total = data.value[0].total;
  };
  function pageSizeChange(size: number) {
    pageConfig.value.pageSize = size;
    search();
  }
  function pageCurrentChange(page: number) {
    pageConfig.value.currentPage = page;
    search();
  }
  proListRun({
    params: {
      index: 1,
      pageSize: 1000,
      blurStr: '',
      state: -1,
    },
  });

  return {
    formRef,
    formConfig,
    formData,
    formItemConfig,
    tableRef,
    pageConfig,
    tableConfig,
    tableColumn,
    tableData,
    proListData,
    search,
    pageCurrentChange,
    pageSizeChange,
  };
}
